package com.hzqy.service.epg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.MD5Util;
import com.hzqy.commons.utils.WChatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class BianfengService {
    private static final Log LOG = LogFactory.getLog(BianfengService.class);

    private final static String BIANFENG_DOMAIN = "http://opiface.gameabc.com";//边锋接口域名
    private final static String BIANFENG_APPID = "20001";
    private final static String BIANFENG_KEY = "nyMgwi62#sYkpA2";
    private final static String TIME_START[] = {"20190325","20190426","20190527"};
    private final static String TIME_END[] = {"20190425","20190526","20190627"};

    public static void main(String[] args) {

    }

    public static String decodeUnicode(String dataStr) {
        //System.out.println("转码前参数："+dataStr);
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(dataStr);
        char ch;
        while (matcher.find()) {
            //group 6728
            String group = matcher.group(2);
            //ch:'木' 26408
            ch = (char) Integer.parseInt(group, 16);
            //group1 \u6728
            String group1 = matcher.group(1);
            dataStr = dataStr.replace(group1, ch + "");
        }
        return dataStr;
    }

    /**
     * 报名信息抛送接口（带iptvid则顺便绑定）
     * phone：手机号码
     * rname：姓名
     * sfz：身份证
     * address：地址
     * iptvid：机顶盒账号
     */
    public static String postSignUp(String phone, String rname, String address, String iptvid) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("rname",URLEncoder.encode(rname, "UTF-8"));
        map.put("address",URLEncoder.encode(address, "UTF-8"));
        map.put("iptvid",iptvid);
        String url = BIANFENG_DOMAIN+"/iptv/userapply";
        return postCommon(map, url, "post");
    }

    /**
     * 绑定信息接口
     * phone：手机号码
     * iptvid：机顶盒账号
     */
    public static String postUserBind(String phone, String iptvid) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("iptvid",iptvid);
        String url = BIANFENG_DOMAIN+"/iptv/userbind";
        return postCommon(map, url, "post");
    }

    /**
     * 重置积分接口
     * phone：手机号码
     */
    public static String postIntegralReset(String phone) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        String url = BIANFENG_DOMAIN+"/iptv/jfreset";
        return postCommon(map, url, "post");
    }

    /**
     * 根据手机查询是否已绑定接口
     * phone：手机号码
     * 根据data.status字段判断，0 已绑定iptvid及边锋账号； 1：未报名；2：报名还未绑定iptvid；3：绑定iptvid，未绑定边锋账号
     */
    public static String getQueryBind(String phone) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        String url = BIANFENG_DOMAIN+"/iptv/querybind";
        return postCommon(map, url, "get");
    }

    /**
     * 用户排行榜接口
     * stage：第几期排行，如2019.03.18-2019.04.18为1，2019.04.19-2019.05.19 为2
     * start：第几名开始取数据
     * top：取出的条数
     * phone：如需要查询当前个人的排行，需要此字段
     */
    public static String getUserRank(String stage, String start, String top, String phone) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("stage",stage);
        map.put("start",start);
        map.put("top",top);
        map.put("phone",phone);
        String url = BIANFENG_DOMAIN+"/iptv/userrank";
        return postCommon(map, url, "get");
    }

    /**
     * 玩家游戏局数
     * phone：所需查询玩家，可批量，不同玩家之间用英文逗号分隔，如：18888888888,15999999999，一次最大20个
     */
    public static String getUserPlayCount(String phone) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        String url = BIANFENG_DOMAIN+"/iptv/userplaycount";
        return postCommon(map, url, "get");
    }

    /**
     * 查询玩家积分
     * stage：第几期排行，如2019.03.18-2019.04.18为1，2019.04.19-2019.05.19 为2
     * phone：所需查询玩家，可批量，不同玩家之间用英文逗号分隔，如：18888888888,15999999999，一次最大20个
     */
    public static String getUserIntegral(String stage, String phone) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("stage",stage);
        map.put("phone",phone);
        String url = BIANFENG_DOMAIN+"/iptv/userjf";
        return postCommon(map, url, "get");
    }

	/**
	 * 明星赛排行
	 */
	public static String selectStarrank(String yesterday) throws IOException {
		Map<String, String> map = new HashMap<>();
		map.put("yesterday", yesterday);
		String url = BIANFENG_DOMAIN+"/iptv/starrank";
		return postCommon(map, url, "get");
	}

    /**
     * 接口调用公共类
     * @throws IOException
     */
    public static String postCommon(Map<String, String> paramMap, String url, String method) throws IOException {
        JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(paramMap));
        String paramStr = String.valueOf(itemJSONObj);
        //System.out.println("param测试数据："+paramStr);
        String paramEncode = EncodeArgs(paramStr, BIANFENG_KEY);
        String encodeParam = UrlEncodeToUper(URLEncoder.encode(paramEncode, "UTF-8"));

        Map<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("appid",BIANFENG_APPID);
        treeMap.put("param",paramEncode);
        String mapStr = sortMapByKey(treeMap);

        String params = "appid="+BIANFENG_APPID+"&param="+encodeParam+"&signature="+mapStr;
        String sendResult = null;

        //System.out.println("请求地址："+url+"?"+params);
        if(method.equals("post")){
            sendResult = WChatUtils.sendPost(url+"?"+params, "");
        }else{
            sendResult = WChatUtils.sendGet(url+"?"+params);
        }
        return sendResult;
    }

    /**
     * 边锋要求param参数编码
     */
    private static String EncodeArgs(String data, String key) {
        int x = 0, len = data.length(), l = key.length(), i;
        String schar = "";
        for (i = 0; i < len; i++) {
            if (x == l) x = 0;
            schar += key.substring(x, x+1);
            x++;
        }
        byte[] strbyte = new byte[len];
        for (i = 0; i < len; ++i) {
            strbyte[i] = (byte)(((int)data.charAt(i) + (int)schar.charAt(i)) % 256);
        }
        return new sun.misc.BASE64Encoder().encode(strbyte);
    }

    /**
     *signature值签名算法
     */
    public static String sortMapByKey(Map<String, String> map){
        if (map == null || map.isEmpty()) {
            return null;
        }
        String result = "";
        try {
            Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
            sortMap.putAll(map);
            for (Map.Entry<String, String> entry : sortMap.entrySet()) {
                result += entry.getKey()+"="+entry.getValue()+"|";
            }
            result += BIANFENG_KEY;
            result = UrlEncodeToUper(result);
            result = MD5Util.MD5Encode(result,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *
     */
    private static String UrlEncodeToUper(String str) throws UnsupportedEncodingException {
        byte[] buf = str.getBytes();
        for (int i = 0; i < buf.length; i++)
            if (buf[i] == '%') {
                if (buf[i + 1] >= 'a')
                    buf[i + 1] -= 32;
                if (buf[i + 2] >= 'a')
                    buf[i + 2] -= 32;
                i += 2;
            }
        return new String(buf, "utf-8");
    }
}

class MapKeyComparator implements Comparator<String>{

    @Override
    public int compare(String str1, String str2) {
        return str1.compareTo(str2);
    }
}